package com.future.hedongjun.mine.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.future.baselib.activity.BaseActivity;
import com.future.baselib.view.LoadingDialog;
import com.future.hedongjun.R;
import com.future.hedongjun.mine.adapter.DeliveryAddressSelectAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * description: 选择收货地址
 * autour: gxcheng
 * date: 2017/9/16 15:17
*/
public class DeliveryAddressSelectActivity extends BaseActivity implements PoiSearch.OnPoiSearchListener{
    @BindView(R.id.delivery_address_selecte_keyword_et)
    EditText mSearchKeyWordEt;
    @BindView(R.id.rv_delivery_address_select)
    RecyclerView mRvDeliveryAddressSelect;
    private DeliveryAddressSelectAdapter mAdapter;
    private List<PoiItem> mAddressList;

    private AMapLocationClient locationClient = null;
    private AMapLocationClientOption locationOption = null;

    private PoiSearch.Query query;// Poi查询条件类
    private PoiSearch poiSearch;
    private PoiResult poiResult; // poi返回的结果
    private LoadingDialog mloadingDialog;
    private LatLonPoint mLp;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_delivery_address_select);
        ButterKnife.bind(this);
        setTitle("选择收货地址");
        mAddressList=new ArrayList<>();
        mloadingDialog=new LoadingDialog(this);
        mloadingDialog.show();

        mRvDeliveryAddressSelect.setLayoutManager(new LinearLayoutManager(this));
        mAdapter=new DeliveryAddressSelectAdapter(R.layout.item_delivery_address_select,mAddressList);
        mRvDeliveryAddressSelect.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                TextView tv= (TextView) view.findViewById(R.id.location_address_tv);
                Intent intent=new Intent();
                intent.putExtra("addressModel",mAddressList.get(position));
                setResult(RESULT_OK,intent);
                finish();
            }
        });


        //初始化定位
        initLocation();
    }

    /*搜索*/
    @OnClick(R.id.delivery_address_search_btn_tv)
    public void doSearchByKeyWord(){
        mloadingDialog.show();
        doSearchQuery(mLp,mSearchKeyWordEt.getText().toString());
    }

    @Override
    protected void getBundleExtras(Bundle extras) {

    }


    /**
     * 初始化定位
     *
     * @since 2.8.0
     * @author gxcheng
     *
     */
    private void initLocation(){
        //初始化client
        locationClient = new AMapLocationClient(this.getApplicationContext());
        locationOption = getDefaultOption();
        //设置定位参数
        locationClient.setLocationOption(locationOption);
        // 设置定位监听
        locationClient.setLocationListener(locationListener);
        // 启动定位
        locationClient.startLocation();
    }
    /**
     * description: 设置默认参数
     * autour: gxcheng
     * date: 2017/9/16 15:52
    */
    private AMapLocationClientOption getDefaultOption(){
        AMapLocationClientOption mOption = new AMapLocationClientOption();
        mOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mOption.setHttpTimeOut(30000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
//        mOption.setInterval(2000);//可选，设置定位间隔。默认为2秒
        mOption.setOnceLocation(true);//可选，设置是否单次定位。默认是false
        mOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        return mOption;
    }

    /**
     * 定位监听
     */
    AMapLocationListener locationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation location) {
            if (null != location) {

                StringBuffer sb = new StringBuffer();
                //errCode等于0代表定位成功，其他的为定位失败，具体的可以参照官网定位错误码说明
                if(location.getErrorCode() == 0){
                    sb.append("定位成功" + "\n");
                    sb.append("定位类型: " + location.getLocationType() + "\n");
                    sb.append("经    度    : " + location.getLongitude() + "\n");
                    sb.append("纬    度    : " + location.getLatitude() + "\n");
                    sb.append("精    度    : " + location.getAccuracy() + "米" + "\n");
                    sb.append("提供者    : " + location.getProvider() + "\n");

                    sb.append("速    度    : " + location.getSpeed() + "米/秒" + "\n");
                    sb.append("角    度    : " + location.getBearing() + "\n");
                    // 获取当前提供定位服务的卫星个数
                    sb.append("星    数    : " + location.getSatellites() + "\n");
                    sb.append("国    家    : " + location.getCountry() + "\n");
                    sb.append("省            : " + location.getProvince() + "\n");
                    sb.append("市            : " + location.getCity() + "\n");
                    sb.append("城市编码 : " + location.getCityCode() + "\n");
                    sb.append("区            : " + location.getDistrict() + "\n");
                    sb.append("区域 码   : " + location.getAdCode() + "\n");
                    sb.append("地    址    : " + location.getAddress() + "\n");
                    sb.append("兴趣点    : " + location.getPoiName() + "\n");
                    //定位完成的时间
//                    sb.append("定位时间: " + Utils.formatUTC(location.getTime(), "yyyy-MM-dd HH:mm:ss") + "\n");
                    mLp=new LatLonPoint(location.getLatitude(),location.getLongitude());
                    doSearchQuery(mLp,location.getStreet());
                } else {
                    mloadingDialog.close();
                    //定位失败
                    sb.append("定位失败" + "\n");
                    sb.append("错误码:" + location.getErrorCode() + "\n");
                    sb.append("错误信息:" + location.getErrorInfo() + "\n");
                    sb.append("错误描述:" + location.getLocationDetail() + "\n");
                    toast("定位失败，请查看是否开启了手机gps定位");
                }
                Log.e("location",sb.toString());
                //定位之后的回调时间
            } else {
                mloadingDialog.close();
//                tvResult.setText("定位失败，loc is null");
            }
        }
    };

    /**
     * 开始进行poi搜索
     */
    /**
     * 开始进行poi搜索
     */
    protected void doSearchQuery(LatLonPoint lp,String keyWord) {
        query = new PoiSearch.Query(keyWord, "", "");// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
        query.setPageSize(20);// 设置每页最多返回多少条poiitem
        query.setPageNum(0);// 设置查第一页

        if (lp != null) {
            poiSearch = new PoiSearch(this, query);
            poiSearch.setOnPoiSearchListener(this);
            poiSearch.setBound(new PoiSearch.SearchBound(lp, 5000, true));//
            // 设置搜索区域为以lp点为圆心，其周围5000米范围
            poiSearch.searchPOIAsyn();// 异步搜索
        }else{
            dissmissLoadingDialog();
            toast("未获取到当前定位点，请打开定位功能以正常使用功能");
        }
    }

    @Override
    public void onPoiSearched(PoiResult poiResult, int i) {
        mAddressList.clear();
        mAddressList.addAll(poiResult.getPois());
        mAdapter.notifyDataSetChanged();
        mloadingDialog.close();
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {
        mloadingDialog.close();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        locationClient.stopLocation();
        locationClient=null;
        locationOption=null;
    }
}
